package cn.ltgodm.template.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.ltgodm.template.common.domain.vo.RoleVO;
import cn.ltgodm.template.common.domain.vo.UserVO;
import cn.ltgodm.template.user.service.MenuService;
import cn.ltgodm.template.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ltgodm
 * @date 2024-03-18 20:42:22
 * 权限服务
 */
@Component
public class PermissionService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    public Set<String> getRolePermission(UserVO user) {
        Set<String> perms = new HashSet<String>();
        //管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("admin");
        } else {
            perms.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return perms;
    }

    public Set<String> getMenuPermission(UserVO user) {
        Set<String> perms = new HashSet<String>();
        //管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            List<RoleVO> roles = user.getRoles();
            if (CollectionUtil.isNotEmpty(roles)){
                for (RoleVO role : roles) {
                    //通过角色查询
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }else {
                //通过用户id查询
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }
}
